package com.yuzhi.master.locations;

import com.yuzhi.master.drainWn.mapper.DrainSludgeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

@Service
public class LocationService {

    @Autowired
    private DrainSludgeMapper drainSludgeMapper;


    @Transactional
    public Long saveLocation(Location location) {
        // 验证坐标点数量
        validateCoordinates(location.getCoordinates());

        // 清空id，让数据库自动生成
        location.setId(null);

        // 插入数据
        int result = drainSludgeMapper.savePoint(location);

        if (result == 0) {
            throw new RuntimeException("插入位置数据失败");
        }
        
        // 返回生成的id
        return location.getId();
    }

    private void validateCoordinates(List<List<Double>> coordinates) {
        if (coordinates == null || coordinates.size() < 3) {
            throw new IllegalArgumentException("多边形至少需要3个坐标点");
        }

        // 确保首尾点相同（多边形闭合）
        List<Double> first = coordinates.get(0);
        List<Double> last = coordinates.get(coordinates.size() - 1);

        if (!first.equals(last)) {
            // 自动添加闭合点
            coordinates.add(new ArrayList<>(first));
        }
    }
}
